#!/usr/bin/env python

import urllib2
import re
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

def submit(filepath, from_addr, metadata):
	try:
		filehandle = open(filepath, "rb")
	except IOError, e:
		print "Error: " + e.strerror
		print "Could not open " + filepath + "for reading"
		sys.exit(1)
		
	register_openers()
	
	url = "http://www.cwsandbox.org/?page=submit&action=verify"
	params = { "email" : from_addr,
				"notification" : "email",
				"upfile" : filehandle }
				
	datagen, headers = multipart_encode(params)
	request = urllib2.Request(url, datagen, headers)
	#request.set_proxy("127.0.0.1:8080", "http")

	# Make the request
	try:
		response = urllib2.urlopen(request)
	except urllib2.URLError, e:
		print e.reason
		print "Submitting to CWSandbox failed..."

	filehandle.close()
	
	the_page = response.read()
	
	if "is being analyzed." or "You have already submitted this sample." or "The sample you have submitted has already been analysed." in the_page:
		try:
			result = re.search("id=(\d+)\S+password=(\w+)", the_page)
			idnum = result.group(1)
			password = result.group(2)
			print "CWSandbox: File submission success, id=" + idnum + " password=" + password
			metadata['CWSandbox'] = "http://www.cwsandbox.org/?page=samdet&id=%s&password=%s" % (idnum, password)	
		except:
			print "CWSandbox: File submission failed"
			print the_page
	else:
		print "CWSandbox: File submission failed"

if __name__ == "__main__":
	import sys
	
	metadata = {}
	
	submit(sys.argv[1], "malware@cryptocity.net", metadata)
	